#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>

enum { START, IFCONF, SHARK, SCANHOST, SCANPORT, DOS, QUIT, END }; 

int menu( void ) {
	system("clear");
	printf("\n\n\n");
	printf("\t###########################################\n");
	printf("\t# %d.查看本机网卡信息                     #\n", IFCONF);
	printf("\t# %d.抓取网络包                           #\n", SHARK);
	printf("\t# %d.扫描主机                             #\n", SCANHOST);
	printf("\t# %d.扫描端口                             #\n", SCANPORT);
	printf("\t# %d.    DOS                              #\n", DOS);
	printf("\t# %d.退出                                 #\n", QUIT);
	printf("\t###########################################\n");
	printf("\t> ");

	int choose;
	do {
		if ( scanf("%d", &choose) != 1 ) {
			while ( getchar() != '\n' );
		} else if ( choose >START && choose < END ) {
				break;
		}
	} while ( 1 );

	return choose;
}

struct {
	int menu_id;
	char *proc;
} menu_maps[] = {
	{START,    NULL},
	{IFCONF,   "./myifconfig"},
	{SHARK,    "./shark"},
	{SCANHOST, "./scanhost"},
	{SCANPORT, "./scanport"},
	{DOS,      "./dos"},
	{END,      NULL}
};

void exec_proc(int menu_id) {
	pid_t pid = fork();
	if ( pid == 0 ) {
		sigset_t set;
		sigemptyset(&set);
		sigaddset(&set, SIGINT);
		sigprocmask(SIG_UNBLOCK, &set, NULL);
		execlp(menu_maps[menu_id].proc, menu_maps[menu_id].proc, NULL);
		perror("execvp");
		exit(0);
	} else {
		waitpid(pid, NULL, 0);
	}
}

void do_quit() {
	printf("谢谢使用，按任意键...\n");
	getchar();
	getchar();
	exit(0);
}

int main( void ) {
	int choose;
	sigset_t set;

	sigemptyset(&set);
	sigaddset(&set, SIGINT);
	sigprocmask(SIG_BLOCK, &set, NULL);
	do {
		choose = menu();
		switch ( choose ) {
		case QUIT:
			do_quit();
		break;
		default:
			exec_proc(choose);
		break;
		}
	} while ( 1 );
}

